#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: tapclient_dataflow.py 
@version:
@time: 2022/06/02 
"""
from TapClientCore.T04_logic.DagNew.dataflow_build.clone_build.clone01base import Clone01Base
from TapClientCore.T05_TM_feature.v1.TMF02_dataflow.tmf_dataflow import TMFV1DataFlow
from TapException.TM import DataFlowBuildError
from TapUtil.decorator.some_useful import timeout
from TapUtil.logfunc.logger import logger


class V1TapclientDataflow(TMFV1DataFlow):
    DATAFLOW_FUNC = {
        'clone': Clone01Base.clone_base01,
        'sync': ...,
    }

    def __query_dataflow_some_by_name(self,
                                      name,
                                      fields=None,
                                      ):
        fields.update({"id": True, "name": True})
        where = {"mappingTemplate": "cluster-clone"}
        limit = 20
        skip = 0
        while True:
            _filter = {
                "order": "createTime DESC",
                "limit": limit,
                "fields": fields,
                "skip": skip,
                "where": where}
            response = self._query_dataflow_by_filter(_filter)
            if response:
                for one in response:
                    if one.get('name') == name:
                        return one
            else:
                break
            skip += limit
        where = {"mappingTemplate": "custom"}
        limit = 20
        skip = 0
        while True:
            _filter = {
                "order": "createTime DESC",
                "limit": limit,
                "fields": fields,
                "skip": skip,
                "where": where}
            response = self._query_dataflow_by_filter(_filter)
            if response:
                for one in response:
                    if one.get('name') == name:
                        return one
            else:
                break
            skip += limit

    # create
    def tap_v1_dataflow_create(self, data):
        record = {}
        dag_name = data.get('dag_name')
        dataflow_config = data.get('dataflow_config')
        dataflow_dag = self.DATAFLOW_FUNC.get(dag_name)
        if dataflow_dag is None:
            raise DataFlowBuildError
        DAG = dataflow_dag(dataflow_config)
        create_response = self.create_dataflow(DAG)
        # 更新
        # create_response = self.patch_dataflow(DAG)
        record['id'] = create_response.get('id')
        record['DAG'] = DAG
        record['create_response'] = create_response
        return record

    # query by name: query
    def tap_v1_dataflow_get_by_name(self, name):
        response = self.__query_dataflow_some_by_name(
            name,
            fields={"id": True, "name": True, "status": True, "executeMode": True, "category": True,
                    "stopOnError": True, "last_updated": True, "createTime": True, "children": True, "stats": True,
                    "checked": True, "stages": True, "setting": True, "user_id": True, "startTime": True,
                    "listtags": True, "mappingTemplate": True, "platformInfo": True, "agentId": True}
        )
        return response

    # query by name: cat_query
    def tap_v1_cat_dataflow_get_by_name(self, name):
        response = self.__query_dataflow_some_by_name(
            name,
            fields={"name": True, "status": True, "setting": True}
        )
        return response

    # query all: more_dataflows
    def tap_v1_dataflow_get_all_dataflow_more(self):
        all_dataflow = []
        fields = {"id": True, "name": True, "status": True, "executeMode": True, "category": True,
                  "stopOnError": True, "last_updated": True, "createTime": True, "children": True, "stats": True,
                  "checked": True, "stages": True, "setting": True, "user_id": True, "startTime": True,
                  "listtags": True, "mappingTemplate": True, "platformInfo": True, "agentId": True}
        where = {"mappingTemplate": "cluster-clone"}
        limit = 20
        skip = 0
        while True:
            _filter = {
                "order": "createTime DESC",
                "limit": limit,
                "fields": fields,
                "skip": skip,
                "where": where}
            response = self._query_dataflow_by_filter(_filter)
            if response:
                for one in response:
                    all_dataflow.append(one)
            else:
                break
            skip += limit
        where = {"mappingTemplate": "custom"}
        limit = 20
        skip = 0
        while True:
            _filter = {
                "order": "createTime DESC",
                "limit": limit,
                "fields": fields,
                "skip": skip,
                "where": where}
            response = self._query_dataflow_by_filter(_filter)
            if response:
                for one in response:
                    all_dataflow.append(one)
            else:
                break
            skip += limit
        return all_dataflow

    # query id, name, status: cat_dataflows
    def tap_v1_dataflow_get_all_dataflow_cat(self):
        all_dataflow = []
        fields = {"id": True, "name": True, "status": True}
        where = {"mappingTemplate": "cluster-clone"}
        limit = 20
        skip = 0
        while True:
            _filter = {
                "order": "createTime DESC",
                "limit": limit,
                "fields": fields,
                "skip": skip,
                "where": where}
            response = self._query_dataflow_by_filter(_filter)
            if response:
                for one in response:
                    all_dataflow.append(one)
            else:
                break
            skip += limit
        where = {"mappingTemplate": "custom"}
        limit = 20
        skip = 0
        while True:
            _filter = {
                "order": "createTime DESC",
                "limit": limit,
                "fields": fields,
                "skip": skip,
                "where": where}
            response = self._query_dataflow_by_filter(_filter)
            if response:
                for one in response:
                    all_dataflow.append(one)
            else:
                break
            skip += limit
        return all_dataflow

    # delete
    def tap_v1_dataflow_delete_by_name(self, name):
        status = self.query_dataflow_some_by_name(name, {'status': True}, get='status')
        logger.info("DELETE DATAFLOW START")
        if not status:
            return f'Not Found {name}'
        elif status in ['paused', 'error', 'draft']:
            self.delete_dataflow_by_name(name)
        else:
            self.stopping_and_wait_to_paused(name)
            self.delete_dataflow_by_name(name)
        logger.info("DELETE DATAFLOW END")

    # reset
    def tap_v1_reset_dataflow(self, name):
        return self.reset_dataflow_by_name(name)

    # run
    def tap_v1_start_dataflow(self, name):
        return self._start_dataflow_by_name(name)

    # stop
    def tap_v1_stop_dataflow(self, name):
        return self._stopping_dataflow_by_name(name)

    # stats
    def tap_v1_get_dataflow_stats(self, name):
        stats = self.query_dataflow_some_by_name(
            name,
            {'stats': True},
            'stats'
        )
        if stats:
            if stats.get('input'):
                self.dataflow_stats = stats
                return stats
